#include "DataController.h"
#include "utils/Logger.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QFileInfo>
#include <QDebug>

DataController::DataController(QObject *parent)
    : QObject(parent),
      m_historyModel(nullptr),
      m_dataRecordModel(nullptr),
      m_csvExporter(new CsvExporter(this)),
      m_isExporting(false),
      m_exportProgress(0),
      m_exportStatus("就绪")
{
    // 连接 CsvExporter 信号
    connect(m_csvExporter, &CsvExporter::exportProgress,
            this, &DataController::onExportProgress);
    connect(m_csvExporter, &CsvExporter::exportFinished,
            this, &DataController::onExportCompleted);
}

DataController::~DataController()
{
}

// 设置历史数据模型
void DataController::setHistoryModel(HistoryModel *model)
{
    m_historyModel = model;
    qDebug() << "DataController: 设置 HistoryModel";
}

// 设置实时数据模型
void DataController::setDataRecordModel(DataRecordModel *model)
{
    m_dataRecordModel = model;
    qDebug() << "DataController: 设置 DataRecordModel";
}

// 查询最近 N 小时数据
bool DataController::queryLastHours(const QString &deviceId, int hours)
{
    qInfo() << "DataController: 查询最近" << hours << "小时数据 - 设备:" << deviceId;

    if (!m_historyModel)
    {
        qWarning() << "DataController: HistoryModel 未设置";
        emit queryFailed("历史数据模型未设置");
        return false;
    }

    bool success = m_historyModel->queryLastHours(deviceId, hours);
    if (success)
    {
        int count = m_historyModel->recordCount();
        emit queryCompleted(true, count);
        Logger::instance()->logOperation("query_data", deviceId,
                                         QString("查询最近 %1 小时，共 %2 条记录").arg(hours).arg(count));
    }
    else
    {
        emit queryFailed("查询失败");
    }

    return success;
}

// 查询最近 N 天数据
bool DataController::queryLastDays(const QString &deviceId, int days)
{
    qInfo() << "DataController: 查询最近" << days << "天数据 - 设备:" << deviceId;

    if (!m_historyModel)
    {
        qWarning() << "DataController: HistoryModel 未设置";
        emit queryFailed("历史数据模型未设置");
        return false;
    }

    bool success = m_historyModel->queryLastDays(deviceId, days);
    if (success)
    {
        int count = m_historyModel->recordCount();
        emit queryCompleted(true, count);
        Logger::instance()->logOperation("query_data", deviceId,
                                         QString("查询最近 %1 天，共 %2 条记录").arg(days).arg(count));
    }
    else
    {
        emit queryFailed("查询失败");
    }

    return success;
}

// 查询今天的数据
bool DataController::queryToday(const QString &deviceId)
{
    qInfo() << "DataController: 查询今日数据 - 设备:" << deviceId;

    if (!m_historyModel)
    {
        emit queryFailed("历史数据模型未设置");
        return false;
    }

    bool success = m_historyModel->queryToday(deviceId);
    if (success)
    {
        int count = m_historyModel->recordCount();
        emit queryCompleted(true, count);
    }
    else
    {
        emit queryFailed("查询失败");
    }

    return success;
}

// 查询昨天的数据
bool DataController::queryYesterday(const QString &deviceId)
{
    qInfo() << "DataController: 查询昨日数据 - 设备:" << deviceId;

    if (!m_historyModel)
    {
        emit queryFailed("历史数据模型未设置");
        return false;
    }

    bool success = m_historyModel->queryYesterday(deviceId);
    if (success)
    {
        int count = m_historyModel->recordCount();
        emit queryCompleted(true, count);
    }
    else
    {
        emit queryFailed("查询失败");
    }

    return success;
}

// 查询日期范围数据
bool DataController::queryDateRange(const QString &deviceId, const QDateTime &start, const QDateTime &end)
{
    qInfo() << "DataController: 查询日期范围 - 设备:" << deviceId
            << "从" << start.toString("yyyy-MM-dd HH:mm:ss")
            << "到" << end.toString("yyyy-MM-dd HH:mm:ss");

    if (!m_historyModel)
    {
        emit queryFailed("历史数据模型未设置");
        return false;
    }

    bool success = m_historyModel->queryDateRange(deviceId, start, end);
    if (success)
    {
        int count = m_historyModel->recordCount();
        emit queryCompleted(true, count);
        Logger::instance()->logOperation("query_data", deviceId,
                                         QString("查询日期范围，共 %1 条记录").arg(count));
    }
    else
    {
        emit queryFailed("查询失败");
    }

    return success;
}

// 查询所有设备数据
bool DataController::queryAllDevices()
{
    qInfo() << "DataController: 查询所有设备数据";

    if (!m_historyModel)
    {
        emit queryFailed("历史数据模型未设置");
        return false;
    }

    m_historyModel->clearFilters();
    bool success = m_historyModel->queryHistoryData();

    if (success)
    {
        int count = m_historyModel->recordCount();
        emit queryCompleted(true, count);
    }
    else
    {
        emit queryFailed("查询失败");
    }

    return success;
}

// 导出到 CSV
bool DataController::exportToCsv(const QString &filePath)
{
    qInfo() << "DataController: 导出数据到 CSV -" << filePath;

    setIsExporting(true);
    updateExportStatus("正在导出...");
    emit exportStarted();

    bool success = m_csvExporter->exportRealtimeData(filePath);

    setIsExporting(false);

    if (success)
    {
        updateExportStatus("导出成功");
        Logger::instance()->logOperation("export_csv", "all", QString("导出数据到: %1").arg(filePath));
    }
    else
    {
        updateExportStatus("导出失败");
        emit exportFailed(m_csvExporter->lastError());
    }

    return success;
}

// 导出指定设备数据
bool DataController::exportDeviceData(const QString &deviceId, const QString &filePath)
{
    qInfo() << "DataController: 导出设备数据 -" << deviceId << "到" << filePath;

    setIsExporting(true);
    updateExportStatus(QString("正在导出设备 %1 的数据...").arg(deviceId));
    emit exportStarted();

    bool success = m_csvExporter->exportRealtimeData(filePath, deviceId);

    setIsExporting(false);

    if (success)
    {
        updateExportStatus("导出成功");
        emit exportCompleted(filePath);
        Logger::instance()->logOperation("export_csv", deviceId, QString("导出数据到: %1").arg(filePath));
    }
    else
    {
        updateExportStatus("导出失败");
        emit exportFailed(m_csvExporter->lastError());
    }

    return success;
}

// 导出日期范围数据
bool DataController::exportDateRange(const QString &deviceId,
                                     const QDateTime &start,
                                     const QDateTime &end,
                                     const QString &filePath)
{
    qInfo() << "DataController: 导出日期范围数据 -" << deviceId
            << "从" << start.toString() << "到" << end.toString();

    setIsExporting(true);
    updateExportStatus("正在导出指定时间范围的数据...");
    emit exportStarted();

    bool success = m_csvExporter->exportRealtimeData(filePath, deviceId, start, end);

    setIsExporting(false);

    if (success)
    {
        updateExportStatus("导出成功");
        emit exportCompleted(filePath);
        Logger::instance()->logOperation("export_csv", deviceId,
                                         QString("导出日期范围数据到: %1").arg(filePath));
    }
    else
    {
        updateExportStatus("导出失败");
        emit exportFailed(m_csvExporter->lastError());
    }

    return success;
}

// 导出当前查询结果
bool DataController::exportCurrentQuery(const QString &filePath)
{
    qInfo() << "DataController: 导出当前查询结果到" << filePath;

    if (!m_historyModel)
    {
        emit exportFailed("历史数据模型未设置");
        return false;
    }

    setIsExporting(true);
    updateExportStatus("正在导出当前查询结果...");
    emit exportStarted();

    // 使用当前 HistoryModel 的过滤条件导出
    QString deviceId = m_historyModel->deviceId();
    QDateTime start = m_historyModel->startTime();
    QDateTime end = m_historyModel->endTime();

    bool success = m_csvExporter->exportRealtimeData(filePath, deviceId, start, end);

    setIsExporting(false);

    if (success)
    {
        updateExportStatus("导出成功");
        emit exportCompleted(filePath);
        Logger::instance()->logOperation("export_csv", deviceId, "导出当前查询结果");
    }
    else
    {
        updateExportStatus("导出失败");
        emit exportFailed(m_csvExporter->lastError());
    }

    return success;
}

// 获取平均温度
double DataController::getAverageTemperature(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        // 临时设置设备过滤
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getAverageTemperature();
}

// 获取平均压力
double DataController::getAveragePressure(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getAveragePressure();
}

// 获取平均流量
double DataController::getAverageFlow(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getAverageFlow();
}

// 获取最大温度
double DataController::getMaxTemperature(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getMaxTemperature();
}

// 获取最大压力
double DataController::getMaxPressure(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getMaxPressure();
}

// 获取最大流量
double DataController::getMaxFlow(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getMaxFlow();
}

// 获取最小温度
double DataController::getMinTemperature(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getMinTemperature();
}

// 获取最小压力
double DataController::getMinPressure(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getMinPressure();
}

// 获取最小流量
double DataController::getMinFlow(const QString &deviceId) const
{
    if (!m_historyModel)
        return 0.0;

    if (!deviceId.isEmpty())
    {
        const_cast<HistoryModel *>(m_historyModel)->setDeviceId(deviceId);
    }

    return m_historyModel->getMinFlow();
}

// 清理实时数据（保留最近 N 天）
bool DataController::clearRealtimeData(int daysToKeep)
{
    qInfo() << "DataController: 清理实时数据，保留最近" << daysToKeep << "天";

    QDateTime cutoffTime = QDateTime::currentDateTime().addDays(-daysToKeep);
    QString condition = QString("timestamp < '%1'").arg(cutoffTime.toString("yyyy-MM-dd HH:mm:ss"));

    bool success = executeDataCleanup("realtime_data", condition);

    if (success)
    {
        Logger::instance()->logOperation("clear_data", "system",
                                         QString("清理实时数据，保留 %1 天").arg(daysToKeep));
    }

    return success;
}

// 清空指定设备的数据
bool DataController::clearDeviceData(const QString &deviceId)
{
    qInfo() << "DataController: 清空设备数据 -" << deviceId;

    QString condition = QString("device_id = '%1'").arg(deviceId);
    bool success = executeDataCleanup("realtime_data", condition);

    if (success)
    {
        // 同时清空实时数据模型中的数据
        if (m_dataRecordModel)
        {
            m_dataRecordModel->clearDeviceData(deviceId);
        }

        Logger::instance()->logOperation("clear_data", deviceId, "清空设备数据");
    }

    return success;
}

// 清空所有数据
bool DataController::clearAllData()
{
    qInfo() << "DataController: 清空所有数据";

    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    int totalRemoved = 0;

    // 清空实时数据
    if (query.exec("DELETE FROM realtime_data"))
    {
        totalRemoved += query.numRowsAffected();
    }

    // 清空分钟统计
    if (query.exec("DELETE FROM minute_statistics"))
    {
        totalRemoved += query.numRowsAffected();
    }

    // 清空小时统计
    if (query.exec("DELETE FROM hour_statistics"))
    {
        totalRemoved += query.numRowsAffected();
    }

    // 清空实时数据模型
    if (m_dataRecordModel)
    {
        m_dataRecordModel->clear();
    }

    emit dataCleared(totalRemoved);
    Logger::instance()->logOperation("clear_data", "system",
                                     QString("清空所有数据，共 %1 条记录").arg(totalRemoved));

    qInfo() << "DataController: 已清空" << totalRemoved << "条记录";
    return true;
}

// 优化数据库
bool DataController::optimizeDatabase()
{
    qInfo() << "DataController: 优化数据库";

    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    // 执行 VACUUM 压缩数据库
    if (!query.exec("VACUUM"))
    {
        qWarning() << "DataController: 数据库优化失败:" << query.lastError().text();
        return false;
    }

    // 分析数据库以更新统计信息
    if (!query.exec("ANALYZE"))
    {
        qWarning() << "DataController: 数据库分析失败:" << query.lastError().text();
    }

    emit databaseOptimized();
    Logger::instance()->logOperation("optimize_db", "system", "数据库优化完成");

    qInfo() << "DataController: 数据库优化完成";
    return true;
}

// 获取实时数据总数
int DataController::getRealtimeDataCount() const
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    if (query.exec("SELECT COUNT(*) FROM realtime_data") && query.next())
    {
        return query.value(0).toInt();
    }

    return 0;
}

// 获取指定设备的数据数量
int DataController::getDeviceDataCount(const QString &deviceId) const
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    query.prepare("SELECT COUNT(*) FROM realtime_data WHERE device_id = ?");
    query.addBindValue(deviceId);

    if (query.exec() && query.next())
    {
        return query.value(0).toInt();
    }

    return 0;
}

// 获取数据库大小
qint64 DataController::getDatabaseSize() const
{
    QFileInfo dbFile(DatabaseService::instance()->database().databaseName());
    return dbFile.size();
}

// 获取有数据的设备列表
QStringList DataController::getDevicesWithData() const
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    QStringList devices;

    if (query.exec("SELECT DISTINCT device_id FROM realtime_data ORDER BY device_id"))
    {
        while (query.next())
        {
            devices.append(query.value(0).toString());
        }
    }

    return devices;
}

// CsvExporter 导出进度
void DataController::onExportProgress(int current, int total)
{
    if (total > 0)
    {
        int progress = (current * 100) / total;
        setExportProgress(progress);
    }
}

// CsvExporter 导出完成
void DataController::onExportCompleted(bool success, const QString &filePath)
{
    setIsExporting(false);

    if (success)
    {
        updateExportStatus("导出成功");
        emit exportCompleted(filePath);
        qInfo() << "DataController: 导出成功 -" << filePath;
    }
    else
    {
        updateExportStatus("导出失败");
        emit exportFailed(m_csvExporter->lastError());
        qWarning() << "DataController: 导出失败 -" << m_csvExporter->lastError();
    }
}

// 更新导出状态
void DataController::updateExportStatus(const QString &status)
{
    if (m_exportStatus == status)
        return;

    m_exportStatus = status;
    emit exportStatusChanged();
}

// 设置导出进度
void DataController::setExportProgress(int progress)
{
    if (m_exportProgress == progress)
        return;

    m_exportProgress = progress;
    emit exportProgressChanged();
}

// 设置导出状态
void DataController::setIsExporting(bool exporting)
{
    if (m_isExporting == exporting)
        return;

    m_isExporting = exporting;
    emit isExportingChanged();

    if (!exporting)
    {
        setExportProgress(0);
    }
}

// 执行数据清理
bool DataController::executeDataCleanup(const QString &tableName, const QString &condition)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    QString sql = QString("DELETE FROM %1 WHERE %2").arg(tableName, condition);

    if (!query.exec(sql))
    {
        qWarning() << "DataController: 数据清理失败:" << query.lastError().text();
        return false;
    }

    int removedCount = query.numRowsAffected();
    emit dataCleared(removedCount);

    qInfo() << "DataController: 清理完成，删除" << removedCount << "条记录";
    return true;
}
